﻿using UnityEngine;
using Mirror;
using System.Collections;

namespace NetTest
{
    public class Projectile:NetworkBehaviour
    {
        public float DestroyTime=2;
      
        public Vector3 Direction;
        public float Speed;
        public override void OnStartServer()
        {
            
            Debug.Log("OnStartServer");
            Invoke(nameof(DestroySelf),DestroyTime);
        }
        public void Shot(Vector3 dir,float speed) 
        {
            StartCoroutine(UpdatePosition());
        }

        private IEnumerator UpdatePosition()
        {
            while (true) 
            {
                transform.position = Vector3.MoveTowards(transform.position, transform.position + Direction.normalized * Speed, Speed * Time.deltaTime);
                yield return null;
            }
        }

        [ServerCallback]
        private void OnTriggerEnter(Collider other)
        {
            if( other.TryGetComponent<ShotPlayer>(out var player)) 
            {
                DestroySelf();
            }
        }

        [Server]
        private void DestroySelf() => NetworkServer.Destroy(gameObject);
        
    }
}
